package com.yfp.operation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.core.constant.CacheConstants;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.ClientIntegralListDTO;
import com.yfp.operation.domain.dto.IntegralHistoryDTO;
import com.yfp.operation.domain.vo.ClientIntegralListVO;
import com.yfp.operation.domain.vo.IntegralHistoryVO;
import com.yfp.operation.mapper.*;
import com.yfp.operation.mapper.*;
import com.yfp.operation.service.ClientIntegralService;
import com.yfp.operation.domain.*;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【client_integral(客户积分)】的数据库操作Service实现
* @createDate 2025-03-05 14:42:03
*/
@Service
public class ClientIntegralServiceImpl extends ServiceImpl<ClientIntegralMapper, ClientIntegral> implements ClientIntegralService{

    @Resource
    private ClientIntegralMapper clientIntegralMapper;
    @Resource
    private OrderListMapper orderListMapper;
    @Resource
    private MallOrderDetailsMapper mallOrderDetailsMapper;
    @Resource
    private OrderComboMapper orderComboMapper;
    @Resource
    private ClientMapper clientMapper;
    @Resource
    private RedissonClient redissonClient;


    /**
     * 积分列表
     * @param clientIntegralListDTO
     * @return
     */
    @Override
    public List<ClientIntegralListVO> clientIntegralList(ClientIntegralListDTO clientIntegralListDTO) {
        return clientIntegralMapper.clientIntegralList(clientIntegralListDTO);
    }

    /**
     * 积分列表数据补全
     * @param list
     * @return
     */
    @Override
    public List<ClientIntegralListVO> clientIntegralListComplement(List<ClientIntegralListVO> list) {

        if (CollUtil.isEmpty(list)) {
            return list;
        }

        List<String> clientIds = list.stream().map(item -> item.getClientId()).toList();

        // 最近交易时间
        List<ClientIntegralListVO> clientIntegralListVOList = clientIntegralMapper.latelyTradingHour(clientIds);
        Map<String, ClientIntegralListVO> cilMap = clientIntegralListVOList.stream().collect(Collectors.toMap(ClientIntegralListVO::getClientId, Function.identity()));

        // 统计收入积分   收入类型    撤销状态
        List<ClientIntegralListVO> incomeIntegralList = clientIntegralMapper.consumeIntegral(clientIds,1, 2);
        Map<String, Integer> incomeIntegralMap = null;
        if (!CollUtil.isEmpty(incomeIntegralList)) {
            incomeIntegralMap = incomeIntegralList.stream().collect(Collectors.toMap(ClientIntegralListVO::getClientId, ClientIntegralListVO::getConsumeIntegral));
        }

        // 统计支出积分   支出类型
        List<ClientIntegralListVO> expendIntegralList = clientIntegralMapper.consumeIntegral(clientIds, 2, null);
        Map<String, Integer> expendIntegralMap = null;
        if (!CollUtil.isEmpty(expendIntegralList)) {
            expendIntegralMap = expendIntegralList.stream().collect(Collectors.toMap(ClientIntegralListVO::getClientId, ClientIntegralListVO::getConsumeIntegral));
        }

        for (ClientIntegralListVO clientIntegralListVO : list) {
            // 交易时间赋值
            if (cilMap.containsKey(clientIntegralListVO.getClientId())) {
                ClientIntegralListVO integralListVO = cilMap.get(clientIntegralListVO.getClientId());
                clientIntegralListVO.setLatelyTradingHour(integralListVO.getLatelyTradingHour());
            }

            if (expendIntegralMap != null && expendIntegralMap.containsKey(clientIntegralListVO.getClientId())) {
                clientIntegralListVO.setConsumeIntegral(expendIntegralMap.get(clientIntegralListVO.getClientId()));
                if (incomeIntegralMap != null && incomeIntegralMap.containsKey(clientIntegralListVO.getClientId())) {
                    clientIntegralListVO.setConsumeIntegral(expendIntegralMap.get(clientIntegralListVO.getClientId()) - incomeIntegralMap.get(clientIntegralListVO.getClientId()));
                }
            }
        }
        return list;
    }


    /**
     * 积分历史记录
     * @param integralHistoryDTO
     * @return
     */
    @Override
    public List<IntegralHistoryVO> integralHistory(IntegralHistoryDTO integralHistoryDTO) {
        List<IntegralHistoryVO> list = clientIntegralMapper.integralHistory(integralHistoryDTO);
        return list;
    }

    /**
     * 积分历史记录数据补全
     * @param list
     * @return
     */
    @Override
    public List<IntegralHistoryVO> integralHistoryComplement(List<IntegralHistoryVO> list) {

        if (CollUtil.isEmpty(list)) {
            return list;
        }

        // 收入订单号
        List<String> incomeOrderIds = list.stream().filter(item -> item.getType().equals(1)).map(item -> item.getOrderId()).toList();
        // 支出订单号
        List<String> expendOrderIds = list.stream().filter(item -> item.getType().equals(2)).map(item -> item.getOrderId()).toList();

        List<OrderListDO> orderListDOS = orderListMapper.getComboNames(incomeOrderIds);
        Map<String, String> comboNameMap = null;
        if (!CollUtil.isEmpty(orderListDOS)) {
            comboNameMap = orderListDOS.stream().collect(Collectors.toMap(OrderListDO::getOrderSn, OrderListDO::getComboName));
        }

        List<MallOrderDetails> mallOrders = mallOrderDetailsMapper.getProductNames(expendOrderIds);
        Map<String, String> productNameMap = null;
        if (!CollUtil.isEmpty(mallOrders)) {
            productNameMap = mallOrders.stream().collect(Collectors.toMap(MallOrderDetails::getOrderSn, MallOrderDetails::getProductName));
        }

        for (IntegralHistoryVO integralHistoryVO : list) {
            if (!CollUtil.isEmpty(comboNameMap) && comboNameMap.containsKey(integralHistoryVO.getOrderId())) {
                integralHistoryVO.setComboName(comboNameMap.get(integralHistoryVO.getOrderId()));
            }
            if (!CollUtil.isEmpty(productNameMap) && productNameMap.containsKey(integralHistoryVO.getOrderId())) {
                integralHistoryVO.setComboName(productNameMap.get(integralHistoryVO.getOrderId()));
            }
        }
        return list;
    }

    /**
     * 订单完成赠送积分
     * @param orderId
     */
    @Override
    @Transactional
    public void giveIntegral(String orderId) {

        OrderComboDO orderComboDO = orderComboMapper.selectById(orderId);

        Client client = clientMapper.getById(orderComboDO.getUserId());

        RLock lock = redissonClient.getLock(CacheConstants.CLIENT_INTEGRAL_LOCK_KEY + client.getId());
        try {
            boolean b = lock.tryLock(5, TimeUnit.SECONDS);
            Assert.isTrue(b, "稍后重试");
            // 添加积分
            if (Objects.nonNull(client)) {
                if (client.getIntegral() == null) {
                    client.setIntegral(0L);
                }
                ClientIntegral clientIntegral = new ClientIntegral();
                clientIntegral.setClientId(orderComboDO.getUserId());
                clientIntegral.setIntegral(new BigDecimal(orderComboDO.getPrice()).intValue());
                clientIntegral.setSource(1);
                clientIntegral.setOrderId(orderId);
                clientIntegral.setStatus(1);
                clientIntegral.setType(1);
                clientIntegral.setSurplusIntegral(client.getIntegral().intValue() + clientIntegral.getIntegral());
                clientIntegralMapper.add(clientIntegral);
                client.setIntegral(client.getIntegral() + clientIntegral.getIntegral());
                clientMapper.edit(client);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            // 释放锁
            lock.unlock();
        }
    }


}




